<template>
    <div class="admin-role-container">
        <div class="mb-4 flex justify-between">
            <el-button type="primary" @click="handleAddRole">新增角色</el-button>
            <el-input v-model="queryParams.keyword" placeholder="请输入角色名称" style="width: 200px" clearable>
                <template #append>
                    <el-button icon="Search" @click="handleSearch" />
                </template>
            </el-input>
        </div>

        <!-- 角色列表 -->
        <el-table v-loading="loading" :data="roleList" style="width: 100%" border>
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="level" label="级别">
                <template #default="scope">
                    <el-tag :type="scope.row.level === 0 ? 'danger' : scope.row.level === 1 ? 'warning' : 'info'">
                        {{ scope.row.level === 0 ? '超级管理员' : scope.row.level === 1 ? '管理员' : '普通角色' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="220" fixed="right">
                <template #default="scope">
                    <el-button v-if="scope.row.id !== 1" link type="primary"
                        @click="handleEditRole(scope.row)">编辑</el-button>
                    <el-button v-if="scope.row.id !== 1" link type="danger"
                        @click="handleDeleteRole(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="mt-4 flex justify-end">
            <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.size"
                :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 角色表单弹窗 -->
        <el-dialog v-model="dialogVisible" :title="formType === 'add' ? '新增角色' : '编辑角色'" width="800px" destroy-on-close>
            <el-form ref="roleFormRef" :model="roleForm" :rules="rules" label-width="100px">
                <el-form-item label="角色名称" prop="role.roleName">
                    <el-input v-model="roleForm.role.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色级别" prop="role.level">
                    <el-select v-model="roleForm.role.level" placeholder="请选择角色级别" style="width: 100%">
                        <el-option :value="1" label="管理员" />
                        <el-option :value="2" label="普通角色" />
                    </el-select>
                </el-form-item>
                <el-form-item label="权限菜单" prop="menuIds">
                    <div class="menu-tree-container">
                        <el-tree ref="menuTreeRef" :data="menuTree" :props="{ label: 'name', children: 'children' }"
                            show-checkbox node-key="id" highlight-current default-expand-all @check="handleMenuCheck" />
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/api'

const loading = ref(false)
const dialogVisible = ref(false)
const formType = ref('add') // 'add' 或 'edit'
const roleList = ref([])
const total = ref(0)
const roleFormRef = ref(null)
const menuTreeRef = ref(null)
const menuTree = ref([])

// 查询参数
const queryParams = reactive({
    page: 1,
    size: 10,
    keyword: ''
})

// 角色表单
const roleForm = reactive({
    role: {
        id: undefined,
        roleName: '',
        level: 2,
        rules: '',
        status: 1
    },
    menuIds: []
})

// 表单校验规则
const rules = {
    'role.roleName': [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '角色名称长度应在2-20个字符之间', trigger: 'blur' }
    ],
    'role.level': [
        { required: true, message: '请选择角色级别', trigger: 'change' }
    ]
}

// 格式化日期
const formatDate = (timestamp) => {
    if (!timestamp) return '--'
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '-')
}

// 获取角色列表
const getRoleList = async () => {
    loading.value = true
    try {
        const res = await adminAPI.getRoleList(queryParams.page - 1, queryParams.size)
        roleList.value = res.data.content
        total.value = res.data.totalElements
    } catch (error) {
        console.error('获取角色列表失败', error)
    } finally {
        loading.value = false
    }
}

// 获取菜单树
const getMenuTree = async () => {
    try {
        const res = await adminAPI.getMenus()
        menuTree.value = res.data
    } catch (error) {
        console.error('获取菜单树失败', error)
    }
}

// 处理搜索
const handleSearch = () => {
    queryParams.page = 1
    getRoleList()
}

// 分页大小变化
const handleSizeChange = (size) => {
    queryParams.size = size
    getRoleList()
}

// 页码变化
const handleCurrentChange = (page) => {
    queryParams.page = page
    getRoleList()
}

// 处理添加角色
const handleAddRole = () => {
    formType.value = 'add'
    roleForm.role = {
        id: undefined,
        roleName: '',
        level: 2,
        rules: '',
        status: 1
    }
    roleForm.menuIds = []

    // 重置菜单选择
    nextTick(() => {
        if (menuTreeRef.value) {
            menuTreeRef.value.setCheckedKeys([])
        }
    })

    dialogVisible.value = true
}

// 处理编辑角色
const handleEditRole = async (row) => {
    formType.value = 'edit'
    loading.value = true

    try {
        const res = await adminAPI.getRoleDetail(row.id)
        roleForm.role = res.data.role
        roleForm.menuIds = res.data.menuIds

        // 设置选中的菜单
        nextTick(() => {
            if (menuTreeRef.value) {
                menuTreeRef.value.setCheckedKeys(roleForm.menuIds)
            }
        })

        dialogVisible.value = true
    } catch (error) {
        console.error('获取角色详情失败', error)
        ElMessage.error('获取角色详情失败')
    } finally {
        loading.value = false
    }
}

// 处理删除角色
const handleDeleteRole = (row) => {
    ElMessageBox.confirm(`确认删除角色 ${row.roleName} 吗？`, '删除确认', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await adminAPI.deleteRole(row.id)
            ElMessage.success('删除成功')
            getRoleList()
        } catch (error) {
            console.error('删除角色失败', error)
            ElMessage.error('删除角色失败')
        }
    }).catch(() => { })
}

// 处理菜单选择
const handleMenuCheck = (node, checkedInfo) => {
    // 获取当前选中的节点
    const checkedKeys = menuTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()

    // 合并完全选中和半选中的节点（保存时需要全部提交）
    roleForm.menuIds = [...checkedKeys, ...halfCheckedKeys]
}

// 提交表单
const submitForm = async () => {
    if (!roleFormRef.value) return

    await roleFormRef.value.validate(async (valid) => {
        if (!valid) return

        // 将菜单ID列表作为rules字段保存（兼容原有结构）
        roleForm.role.rules = roleForm.menuIds.join(',')

        try {
            if (formType.value === 'add') {
                await adminAPI.createRole(roleForm)
                ElMessage.success('创建成功')
            } else {
                await adminAPI.updateRole(roleForm.role.id, roleForm)
                ElMessage.success('更新成功')
            }

            dialogVisible.value = false
            getRoleList()
        } catch (error) {
            console.error('保存角色失败', error)
            ElMessage.error('保存角色失败')
        }
    })
}

// 页面初始化
onMounted(() => {
    getRoleList()
    getMenuTree()
})
</script>

<style scoped>
.admin-role-container {
    padding: 20px;
}

.menu-tree-container {
    height: 400px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
}
</style>
